﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QD.Snapshot.Core.Util;
using NSoup.Select;
using NSoup.Nodes;
using Pigeon.Utility;
using QD.Snapshot.Core.Config;

namespace QD.Snapshot.Core.BLL
{
    public abstract class SearchBase
    {
        public bool IsCode_BD { get; set; }
        public bool IsCode_360 { get; set; }
        public bool IsCode_Sogou { get; set; }
        public bool IsCode_Bing { get; set; }
        public bool IsCode_GuoSou { get; set; }
        public bool IsCode_WX { get; set; }

        public TextBox textBox { get; set; }

        /// <summary>
        /// 休眠时间（单位秒）
        /// </summary>
        public int SleepTime { get; set; }

        /// <summary>
        /// 搜索引擎 0 百度,1 360, 2 搜狗,3 bing, 4中国搜索, 5 搜狗微信
        /// </summary>
        public string copyform { get; set; }

        /// <summary>
        /// 搜索
        /// </summary>
        public abstract void Search(string keyword, Model.Product product, Model.WebSite company);

        protected virtual void RemoveAttr(Elements result) { }

        public void Search()
        {
            List<Model.Product> list = Product.GetList(copyform);

            if (list == null)
            {
                EchoLog("search", string.Format("没有产品"));
                Thread.Sleep(10000);
                return;
            }
            int keywordCount = 0;
            string ids = "", article_ids = "";

            GetIds(list, out ids, out article_ids, out keywordCount);

            EchoLog("search", string.Format("获取{0}条,任务数{1},itemid:{2}", list.Count, keywordCount, list[0].itemid));

            Product.UpdateTime(copyform, ids, article_ids); //更新时间

            Dictionary<int, Model.WebSite> listCompany = WebSite.GetList(list);  //获取公司
            if (listCompany == null)
            {
                EchoLog("search", string.Format("公司不存在,ids:{0},article_ids:{1}", ids, article_ids));
                return;
            }
            foreach (var item in list)
            {
                foreach (var key in item.keywords)
                {
                    //int itemid = item.productid > 0 ? item.productid : item.articleid;
                    Search(key, item, listCompany[item.userid]);  //查询
                }
            }
        }


        /// <summary>
        /// 添加匹配成功的任务队列，等待队列中执行的上传
        /// </summary>
        protected void AddSnap(Model.Snap model) {
            Echo(string.Format("{0} 页{1} 行{2} 匹配成功", model.keyword, model.page, model.ranking));
            Logs("search", string.Format("{0}-{1}-[{2}]-{3} 页{4} 行{5} 匹配成功", model.userid, model.itemid, GetCopyform(copyform), model.keyword, model.page, model.ranking));
        }

        /// platform = platform,<summary>
        /// updatetime = DateTime.Now,返回加密的MD5 前8位
        /// index_key = UrlMd5,</summary>
        /// html = html<param name="str"></param>
        /// <returns></returns>
        protected string GetMd5(String str)
        {
            if (string.IsNullOrEmpty(str)) return "";
            str = Encrypt.MD5(str);
            return str.Substring(0, 8);
        }

        /// <summary>
        /// 勤加缘匹配
        /// </summary>
        /// <returns></returns>
        protected bool CheckQJY(string html, Regex SiteName, Regex Cellphone, Regex phone)
        {
            if (html.IndexOf("qjy168.com") == -1) return false;
            if (SiteName.IsMatch(html) || Cellphone.IsMatch(html) || phone.IsMatch(html))
                return true;
            return false;
        }

        protected bool CheckShortNameList(string html)
        {
            return false;
        }

        /// <summary>
        /// 检查是否出现验证码
        /// </summary>
        protected bool CheckCode(string html)
        {
            if (html.Contains("异常的访问") || html.Contains("以下验证码") || html.Contains("您的访问出错了") || html.Contains("请求异常频繁") || html.Contains("访问为正常用户行为") || html.Contains("antispider"))
                return true;
            return false;
        }

        protected string FixRegex(string Pattern)
        {
            if (string.IsNullOrEmpty(Pattern)) return string.Empty;
            return Regex.Replace(Pattern, @"\(|\)|\\|\*|\?|\.|\+|\[|\]", @"\$0");
        }
        /// <summary>
        /// 获取平台ID
        /// </summary>
        protected string GetPlatform(string html)
        {
            string domain = "";
            if (UrlDomain.Domain != null)
            {
                Dictionary<string, string>.Enumerator em = UrlDomain.Domain.GetEnumerator();
                while (em.MoveNext())
                {
                    if (html.IndexOf(em.Current.Value) > 0) //站点匹配成功
                    {
                        domain = em.Current.Key;
                        break;
                    }
                }
            }
            return domain;
        }

        protected void HideElementList(Elements eleList)
        {
            if (eleList == null) return;
            foreach (Element ele in eleList)    //去掉每行 左边图片
                HideElement(ele);
        }

        protected void HideElement(Element ele)
        {
            if (ele == null) return;
            ele.Html("");
            ele.Attributes["style"] = "display:none";
        }

        protected void Echo(string msg)
        {
            EchoHelper.ShowMessage(textBox, string.Format("{0} {1}", DateTime.Now.ToString("MM-dd HH:mm:ss"), msg));
        }

        protected void Logs(string filename, string msg)
        {
            Log.Write(string.Format("{0}_{1}.log", filename, DateTime.Now.ToString("yyyyMMdd")), msg);
        }

        protected void EchoLog(string filename, string msg)
        {
            Echo(msg);
            Pigeon.Utility.Log.Write(string.Format("{0}_{1}.log", filename, DateTime.Now.ToString("yyyyMMdd")), msg);
        }

        public void EchoCodeLog(EngineType engineType, string msg)
        {
            Echo(msg);
            MsgHelper.SendCodeMessage(msg, engineType);
            Log.Write(string.Format("code_{0}.log", DateTime.Now.ToString("yyyyMMdd")), msg);
        }

        void GetIds(List<Model.Product> listId, out string ids, out string article_ids, out int keywordCount)
        {
            ids = article_ids = "";
            keywordCount = 0;
            if (listId == null) return;

            StringBuilder sb = new StringBuilder();
            StringBuilder sb_articleid = new StringBuilder();
            foreach (var item in listId)
            {
                if (item.productid > 0)
                    sb.AppendFormat(",{0}", item.productid);            //产品ID

                if (item.articleid > 0)
                    sb_articleid.AppendFormat(",{0}", item.articleid);  //软文ID

                keywordCount += item.keywords.Count;        //关键词数
            }

            if (sb.Length > 0)
                ids = sb.ToString().Substring(1);

            if (sb_articleid.Length > 0)
                article_ids = sb_articleid.ToString().Substring(1);
        }

        string GetCopyform(string copyform)
        {
            //string[] arrCopyform = { "百度", "360", "搜狗", "Bing", "中国搜索", "搜狗微信" };
            //return arrCopyform[Convert.ToInt32(copyform)];
            return Engine.EngineTitle[Convert.ToInt32(copyform)];
        }
    }
}